#!/usr/bin/env groovy Jenkinsfile
// 定义环境变量属性-需要更改
def git_url="{{.AppInfo.GitlabUrl}}"
//def projectname="{{.AppConfig.AppsName}}"
def code_filename="{{.AppConfig.PackageName}}"   // 包名
def healthcheck="{{.AppConfig.HealthCheck}}"
def deploy_env="{{.AppConfig.DeployEnv}}"
def jar_target_dir="{{.AppConfig.BuildPath}}" // mvn生成jar包的相对workspace目录 或者直接写绝对路径 或者从ftp下载的目录


// 定义环境变量属性-无需要更改
def credentialsId = "67bbe554-b961-48e9-bdbb-ea80dd8b41c0"
def ssh = "ssh -o StrictHostKeyChecking=no"
def scp = "scp -o StrictHostKeyChecking=no"
def deploy_user = "appuser"
def code_dir = "{{.AppConfig.DeployPath}}"   // 项目部署路径
def test_ssh_command = 'echo check ssh connection' //定义host1 ssh remote 测试远程执行命令变量
def mkdir_codedir_cmd="mkdir -p ${code_dir}"
def exeute_deploy_script_cmd="{{.AppConfig.DeployRun}}"

node {
    try {
        // 服务是否重启判断
      if (ifRestart == "false") {
        stage('拉取代码') {
            git branch: "${BRANCH}", credentialsId: credentialsId, url: git_url
        }
        stage('编译代码') {
            sh "{{.AppConfig.BuildRun}}"
            //sh "echo 跳过编译"
        }
        stage('上传ftp') {
            sh "goftp -h test-ftp-01 -p 21 -u deploy_user -p deploy_p@ssword -m upload -s ${jar_target_dir}/${code_filename} -d {{.AppConfig.ProjectCode}}/{{.AppConfig.DeployEnv}}/{{.AppConfig.AppsName}}/${currentVersion}"
        }
      }

    {{range .CmdbVirtualList }}
      if (ifRestart == "false") {
        stage('部署代码-{{.Ipaddress}}') {
            //1. 测试remote host连通性
            sh "${ssh} ${deploy_user}@{{.Ipaddress}} ${test_ssh_command}"
            //2. 创建远程代码目录
            sh "${ssh} -tt ${deploy_user}@{{.Ipaddress}} ${mkdir_codedir_cmd}"
            //4. 拷贝jar包代码到远程目录
            sh "${scp} ${jar_target_dir}/${code_filename} ${deploy_user}@{{.Ipaddress}}:${code_dir}"
        }
      }
        stage('重启服务-{{.Ipaddress}}') {
            //1. 执行发布脚本 部署日志远端机器: /tmp/.deploy.log
            sh "${ssh} -tt ${deploy_user}@{{.Ipaddress}} \"${exeute_deploy_script_cmd}\""
        }
    {{end}}
    } catch (e) {
     	//echo 'This will run only if failed'
     	currentBuild.result = 'FAILURE'
     	throw e
    } finally {
        def currentResult = currentBuild.result ?: 'SUCCESS'
        if (currentResult == 'UNSTABLE') {
            echo 'This will run only if the run was marked as unstable'
            } else if (currentResult == 'FAILURE') {
                echo 'This will run only if the run was marked as FAILURE'
        	} else {
                echo 'This will run only if the run was marked as SUCCESS'
        	}
        	sh "curl -m 10 --retry 3 -s 'http://luban.anji-plus.com/api/base/deploy/notify?job_name=${JOB_NAME}&build_number=${BUILD_NUMBER}&build_status=${currentResult}'"
    }

}